﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace MendeleyClient.Phone
{
    public partial class DocumentPage : PhoneApplicationPage
    {
        string searchTerm = "";
        SearchViewModel searchViewModel;

        // Constructor
        public DocumentPage()
        {
            InitializeComponent();

            searchViewModel = new SearchViewModel();
            // Set the data context of the listbox control to the sample data
            this.LayoutDocument.DataContext = searchViewModel;

            this.Loaded += new RoutedEventHandler(StatPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void StatPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.TitleBarTextBlock.Text = "Search";
            if (!searchViewModel.IsDataLoaded)
            {
                searchViewModel.LoadData(searchTerm);
            }
            RefreshData();
        }

        private void RefreshData(bool force = false)
        {
            this.RefreshProgressBar.Visibility = System.Windows.Visibility.Visible;
            if (force)
            {
                searchViewModel.Items.Clear();
                searchViewModel.IsDataLoaded = false;
            }
            searchViewModel.LoadData(searchTerm);
            this.RefreshProgressBar.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void RefreshAppBarIcon_Click(object sender, System.EventArgs e)
        {
        	RefreshData(true);
        }
		
        private void MendeleyIcon_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void Search_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            searchTerm = SearchAutoCompleteBox.Text;
            RefreshData(true);
        }

        private void AuthorListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                SearchItemViewModel rec = (SearchItemViewModel)e.AddedItems[0];
                DocumentTextBlock.Text += rec.Title;
                DocumentTextBlock.Text += "\n";
                DocumentTextBlock.Text = rec.Authors;
                DocumentTextBlock.Text += "\n";
                DocumentTextBlock.Text += rec.Publication;
                DocumentTextBlock.Text += "\n";
                DocumentTextBlock.Text += rec.Year;
            }
            Pivot.SelectedIndex = 1;
        }
    }
}